/* eslint-disable no-unused-vars */
import api from '@/api/index.js'
import {setToken,getToken,removeToken} from '@/utils/auth'
import { post, get, From, postJson,deleteData } from '@/api/request'//真实请求
const state = {
    code:'',//验证码
    token:getToken(),//token
    userInfo:{},//用户信息
}

const mutations = {
    GETCODE(state, data) {
        state.code = data
    },
    USERLOGIN(state, data) {
        state.token = data
    },
    GETUSERINFO(state, data) {
        state.userInfo = data
    },
    CLEAR_USER_INFO(state) {
        state.userInfo = {},
        state.token=''
    }
}

const actions = {
    getCode({ commit }, phone) {//获取验证码
        return new Promise((resolve,reject)=>{
        get(`${api.getCode}/${phone}`).then(res=>{
            commit('GETCODE',res.data)
            resolve(res)
        }).catch(err=>{
            reject(err)
        });
        
        })
    },
    userRegister({ commit }, data) {//注册
        return new Promise((resolve,reject)=>{
            postJson(api.userRegister,data).then(res=>{
                if(res.code == 200){
                    resolve(res)
                }
               
            }).catch(err=>{
                reject(err)
            });
        
        })
    },
    userLogin({ commit }, data) {//登录
        return new Promise((resolve,reject)=>{
            postJson(api.userLogin,data).then(res=>{
                if(res.code == 200){
                    commit('USERLOGIN',res.data.token)
                    setToken(res.data.token)
                    resolve(res)
                }
            }).catch(err=>{
                reject(err)
            });
        
        })
    },
    getUserInfo({ commit }, data) {//获取用户信息
        return new Promise((resolve,reject)=>{
            get(api.userInfo).then(res=>{
                if(res.code == 200){
                    commit('GETUSERINFO',res.data)
                    resolve(res)
                }
            }).catch(err=>{
                reject(err)
            });
        })
    },
    userLogout({ commit }, data) {//退出登录
        return new Promise((resolve,reject)=>{
            get(api.logout).then(res=>{
                if(res.code==200){
                    commit('CLEAR_USER_INFO')//清除用户信息
                    removeToken()
                    resolve(res)
                }
            }).catch(err=>{
                reject(err)
            });
        })
    }

}

export default {
    state,
    mutations,
    actions
}
